<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="bootstrap/css/bootstrap.css">
    <script src="js/jquery.min.js"></script>
</head>

<body>

    <input type="file" name="" id="file1">
    <button id="btnUpload">上传文件</button>


    <div class="progress" style="width: 500px; margin: 15px 10px;">
        <div class="progress-bar progress-bar-striped active" aria-valuemax="100" style="width: 0%;" id="percent">
            0%
        </div>
    </div>
    <!-- 进度条 -->

    <br>
    <img src="" alt="" width="800" id="img">



    <script>
        var btnUpload = document.querySelector('#btnUpload');
        btnUpload.addEventListener('click', function () {
            var files = document.querySelector('#file1').files;
            if (files.length <= 0)
                return alert('请选择要上传的文件')


            var fd = new FormData();
            fd.append('avatar', files[0])
            //将用户选择的文件添加到FormData中

            var xhr = new XMLHttpRequest();



            xhr.upload.onprogress = function (e) {
                if (e.lengthComputable) {
                    //计算上传的进度
                    var procentComplete = Math.ceil((e.loaded / e.total) * 100);
                    // console.log(procentComplete);
                    // 动态设置进度条
                    $('#percent').attr('style', 'width:' + procentComplete + '%').html(procentComplete + '%');

                }
            }

            // 监听上传完成的的事件
            xhr.upload.onload = function () {
                $('#percent').removeClass().addClass('progress-bar progress-bar-success');
            }


            xhr.open('POST', 'http://www.liulongbin.top:3006/api/upload/avatar');
            xhr.send(fd);

            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    var data = JSON.parse(xhr.responseText);
                    if (data.status === 200)
                        document.querySelector('#img').src = 'http://www.liulongbin.top:3006' + data.url
                    else
                        console.log(data.message);
                }
            }
        })

    </script>

</body>

</html>